import Vue from 'vue'
import Vuex from 'vuex'
import moduleProduct from './module/product'

Vue.use(Vuex)


var constStore ={
  //初始 state mutations 对象
  state:{
    count:0,
    todos:[
      {id: 1,title: '123',done: true},
      {id: 2,title: '133',done: true},
      {id: 3,title: '223',done: false},
      {id: 4,title: '122',done: true}
    ],
    userName:'小彭',
  },
  mutations:{
    increament1:function(state){
      state.count++
    },
    increament2:function(state,num){
      state.count += num
    },
    increament3:state =>{
      state.count++
    },
    increamentBy:(state,num)=>{
      state.count += num
    },
    updateUserName:(state,newUserName)=>{
      state.userName = newUserName
    }
  },
  //getter 的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算
  getters:{
    todoDone:state=>{
      return state.todos.filter(item=>item.done===true)
    },
    todoDoneCount:(state,getters)=>{
      return getters.todoDone.length
    },
    userNameOK:state=>{
      return '大自然的搬运工'+state.userName
    }
  },
  actions:{
    getUserInfo:({commit},parm)=>{
      //ctx.state.userName = token
      setTimeout(()=>{
        console.log('两秒后执行')
      },2000)
      commit('updateUserName',parm.token)//先打印了这个   异步
    }
  },
  modules:{
    moduleProduct//引入一个模块
    //product:moduleProduct//product子模块
  }
}
//state，驱动应用的数据源；
//创建一个 store
const store = new Vuex.Store(constStore)
  
  console.log(store.state.count)//0   通过 store.state 来获取状态对象
  
  store.commit('increament1')   //通过 store.commit 方法触发状态变更
  console.log(store.state.count)//1
  
  store.commit('increament2',90)
  console.log(store.state.count)//91
  
  console.log('---------------------------')
  store.commit('increament3')

  export default store